<?php

namespace app\company\controller;

use app\admin\model\product\Category;
use app\common\controller\CompanyApi;

/**
 * 首页接口
 */
class Productcategory extends CompanyApi
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 物资分类
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $lists = \app\admin\model\product\Category::field('id,title,image')->where('status', 'normal')->where('department_id', $user->department_id)->select();
        $this->success('分类列表', $lists);
    }

    /**
     * 新增分类
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create()
    {
        $title = $this->request->post('title');
        $image = $this->request->post('image');
        if (!$title) {
            $this->error('分类名称必填');
        }

        $user = $this->auth->getUser();
        $cinfo = Category::where('title', $title)
            ->where('department_id', $user->department_id)
            ->find();
        if ($cinfo) {
            $this->error('该分类已存在！');
        }

        $data = [
            'title' => $title,
            'image' => $image,
            'department_id' => $user->department_id
        ];

        $ret = Category::create($data);
        if (!$ret) {
            $this->error('新增失败');
        }

        $this->success('新增成功');
    }
}
